package com.wxjfkg.workflow.impl;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.*;

import com.fivestar.credit.service.CreditLimitService;
import com.fivestar.credit.service.vo.ApplyCredTakeProdDto;
import com.fivestar.credit.service.vo.CreditConstants;
import com.fivestar.creditperson.service.CreditUserLimitService;
import com.fivestar.customer.service.CustomerService;
import com.fivestar.customer.service.vo.CustomerDto;
import org.activiti.engine.delegate.DelegateExecution;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fivestar.app.vo.AppConstants;
import com.fivestar.app.vo.AppMessageVO;
import com.fivestar.appmsg.service.AppMsgService;
import com.fivestar.credit.service.ApplyCreditService;
import com.fivestar.credit.service.vo.ApplyCredTakeDto;
import com.fivestar.loan.service.vo.ApplyConstants;
import com.fivestar.merchant.service.MerchantService;
import com.fivestar.merchant.service.vo.MerchantInfoDto;
import com.fivestar.query.vo.ResultDto;
import com.fivestar.util.date.DateTimeUtils;
import com.wxjfkg.workflow.BeforeEndTaskService;

@Service("applyTakeFailTaskServiceImpl")
public class ApplyTakeFailTaskServiceImpl implements BeforeEndTaskService {

	public Logger logger = LoggerFactory.getLogger(ApplyTakeFailTaskServiceImpl.class);
	@Autowired
	private ApplyCreditService applyCreditService;
	@Autowired
	private AppMsgService appMsgService;
	@Value("${loanUseMsgContent}")
	private String loanUseMsgContent;
	@Autowired
	private MerchantService merchantService;

	@Autowired
	private CustomerService customerService;

	//店铺授信额度service
	@Autowired
	private CreditLimitService creditLimitService;

	//个人授信额度service
	@Autowired
	private CreditUserLimitService creditUserLimitService;

	@Override
	@Transactional(value="txTranManager")
	public void execute(DelegateExecution execution) throws Exception {
		String bussKey = execution.getProcessBusinessKey();
		logger.info("用信编号{}",bussKey);
		if(StringUtils.isNotEmpty(bussKey)){
			ApplyCredTakeDto creditTake = new ApplyCredTakeDto();
			creditTake.setApplyId(bussKey);
			ResultDto<ApplyCredTakeDto> retTake = applyCreditService.queryApplyCreditDetail(creditTake);
			if(retTake.isSuccess() && retTake.getData() != null) {
				creditTake = retTake.getData();
				//=====恢复添加用信申请时扣去的授信额度start====

				//贷款产品按授信品种分类累加的贷款金额
				Map<String, BigDecimal> loanAmtGroupByCreditType = new HashMap<>();
				for(ApplyCredTakeProdDto prod : creditTake.getProds()) {
					String creditType = prod.getCreditType();
					if(loanAmtGroupByCreditType.get(creditType) == null) {
						loanAmtGroupByCreditType.put(creditType, prod.getLoanAmt());
					}
					else {
						BigDecimal currentSum = loanAmtGroupByCreditType.get(creditType);
						loanAmtGroupByCreditType.put(creditType, currentSum.add(prod.getLoanAmt()));
					}
				}
				for(String creditType : loanAmtGroupByCreditType.keySet()) {
					//todo 额度交易类型换成用信审批拒绝
					//店铺
					if(com.fivestar.util.str.StringUtils.isNotEmpty(creditTake.getMerchId())) {
						creditLimitService.mergeCreditLimit(creditTake.getMerchId(), creditType,
								loanAmtGroupByCreditType.get(creditType), CreditConstants.CREDIT_BUSS_TYPE.USE,
								creditTake.getApplyId(), CreditConstants.CREDIT_DIRECT.HUAN);
					}
					//个人
					if(com.fivestar.util.str.StringUtils.isNotEmpty(creditTake.getCustId())) {
						creditUserLimitService.changeCreditUserLimit(creditTake.getCustId(), creditType,
								loanAmtGroupByCreditType.get(creditType), CreditConstants.CREDIT_BUSS_TYPE.USE,
								creditTake.getApplyId(), CreditConstants.CREDIT_DIRECT.HUAN);
					}
				}

				//=====恢复添加用信申请时扣去的授信额度end====

				//更新用信申请状态
				ApplyCredTakeDto apply = new ApplyCredTakeDto();
				apply.setAppStat(ApplyConstants.DiscountStatusEnum.STATE_REFUSE.getStatusCode());
				apply.setApplyId(bussKey);
				applyCreditService.mergeApplyCredStat(apply);
				//生成提醒消息到消息列表
				AppMessageVO messageVO = new AppMessageVO();
				messageVO.setMsgSubType(AppConstants.APP_MSG_SUBTYPE.WALLET);
				messageVO.setMsgTitle("贷款提醒");
				//从内容模板生成提醒消息内容
				String prodName = "";
				if(CreditConstants.CREDIT_USE_TYPE.JH.equals(creditTake.getLoanUse())){
					prodName = "进货";
				}else if(CreditConstants.CREDIT_USE_TYPE.NQ.equals(creditTake.getLoanUse())){
					prodName = "拿钱";
				}
				//申请用户名称
				String applicantName = null;
				//申请用户登录账号
				String applicantLoginId = null;
				//店铺
				if(StringUtils.isNotEmpty(creditTake.getMerchId())) {
					MerchantInfoDto merchantInfo = new MerchantInfoDto();
					merchantInfo.setMerchId(creditTake.getMerchId());
					List<MerchantInfoDto> merchantInfoList = merchantService.qryMerchantList(merchantInfo);
					if (merchantInfoList != null && !merchantInfoList.isEmpty()) {
						merchantInfo = merchantInfoList.get(0);
					}
					applicantName = merchantInfo.getMerchName();
					applicantLoginId = merchantInfo.getMerchRelatedMobile();
				}
				//个人
				else if(StringUtils.isNotEmpty(creditTake.getCustId())) {
					CustomerDto customerDto = new CustomerDto();
					customerDto.setCustId(creditTake.getCustId());
					List<CustomerDto> customerDtoList = customerService.qryCustomerList(customerDto);
					if(customerDtoList != null && !customerDtoList.isEmpty()) {
						customerDto = customerDtoList.get(0);
					}
					applicantName = customerDto.getCustName();
					//todo 待确认服务中心后台登录方式
					applicantLoginId = customerDto.getCustId();
				}
		        String content = MessageFormat.format(loanUseMsgContent, applicantName,
						bussKey.substring(bussKey.length() - 4), prodName, "审批未通过");
		        messageVO.setMsgContent(content);
		        messageVO.setContentSource(bussKey);
		        Date now = new Date();
		        //消息有效时间为提醒时间当天至次日
		        messageVO.setStartTime(now);
		        messageVO.setEndTime(DateTimeUtils.getUpdateDateTime(now, Calendar.DAY_OF_MONTH, 1));
		        messageVO.setLoginId(applicantLoginId);
				appMsgService.createXbtBusinessMsg(messageVO);
			}else{
				logger.error("查询用信申请信息失败"+bussKey);
			}
		}
	}
}
